package com.qulei.demo.dao;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.qulei.demo.db.dao.DBBaseDao;
import com.qulei.demo.db.utils.DBHelper;
import com.qulei.demo.db.utils.DBObserver;

public class DaoFactory implements DBObserver {

	private static DaoFactory INSTANCE;

	private Context mContext;

	private HashMap<String, DBBaseDao<?>> mapObject = null;

	private final static ArrayList<Class<?>> listClass = new ArrayList<Class<?>>() {
		private static final long serialVersionUID = 1L;
		{
			add(PersonDao.class);
		}
	};

	private DaoFactory(Context context) {
		this.mContext = context;
		mapObject = new HashMap<String, DBBaseDao<?>>();
	}

	public static DaoFactory getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new DaoFactory(context);
		}
		return INSTANCE;
	}

	public void initialize() {
		DBHelper.getInstance(mContext).addObserver(INSTANCE);
	}

	public void release() {
		DBHelper.getInstance(mContext).deleteObserver(INSTANCE);
		DBHelper.getInstance(mContext).release();
		mapObject.clear();
		mapObject = null;
		INSTANCE = null;
	}

	public DBBaseDao<?> createHuman(Class<?> c) {
		DBBaseDao<?> dao = null;
		try {
			if (mapObject.containsKey(c.getSimpleName())) {
				dao = mapObject.get(c.getSimpleName());
			} else {
				dao = (DBBaseDao<?>) Class.forName(c.getName()).newInstance();
				mapObject.put(c.getSimpleName(), dao);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return dao;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		for (Class<?> item : listClass) {
			DBBaseDao<?> dao = (DBBaseDao<?>) createHuman(item);
			if (dao != null) {
				Log.d("qulei", "onCreate");
				dao.onCreateDataBase(db);
			}
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		for (Class<?> item : listClass) {
			DBBaseDao<?> dao = (DBBaseDao<?>) createHuman(item);
			if (dao != null) {
				dao.ononUpgradeDataBase(db, oldVersion, newVersion);
			}
		}
	}

}
